#include "include.h"

/****************************************************************
 *This function is thread11
 *	(1)create socket,listen port,process command
 ****************************************************************/
void *thread11(void *str)
{
	// 接收组播部分
	int socked;  
	struct sockaddr_in local_addr;
	struct ip_mreq mreq; // 多播地址结构体
	char rev_buffer[4096];
	int rev_length = 0;
	struct sockaddr_in sender;
	unsigned int sender_len = sizeof(struct sockaddr_in);

	// 清空局部变量
	memset(&local_addr,0,sizeof(local_addr));

	// 建立socket
	socked=socket(AF_INET,SOCK_DGRAM,0); 

	// 填充组播信息
	local_addr.sin_family=AF_INET;
	local_addr.sin_addr.s_addr=htonl(INADDR_ANY);
	//local_addr.sin_addr.s_addr=inet_addr(ONE_LO_PCM_DEV_IP);
	local_addr.sin_port=htons(ONE_LO_PCM_BOARDCAST_PORT);

	// 绑定本地端口
	bind(socked,(struct sockaddr*)&local_addr,sizeof(local_addr));

	// 加入组播组
	mreq.imr_multiaddr.s_addr=inet_addr(ONE_LO_PCM_BOARDCAST_IP);
	mreq.imr_interface.s_addr = inet_addr(ONE_LO_PCM_DEV_IP);
	setsockopt(socked,IPPROTO_IP,IP_ADD_MEMBERSHIP,&mreq,sizeof(mreq));

	// 建立应答组播socket
    // 建立应答组播套接字
	int sock_send;
	sock_send = socket(AF_INET, SOCK_DGRAM, 0);

	struct in_addr opt;
    inet_pton(AF_INET, ONE_NET_PCM_BOARDCAST_IP, &opt.s_addr);
    setsockopt(sock_send, IPPROTO_IP, IP_MULTICAST_IF, &opt, sizeof(opt));
    struct sockaddr_in cliaddr;
    int len = sizeof(cliaddr);
    cliaddr.sin_family = AF_INET;
    cliaddr.sin_port = htons(BOARDCAST_REV_PCM_PORT);
    inet_pton(AF_INET, ONE_NET_PCM_BOARDCAST_IP, &cliaddr.sin_addr.s_addr);

	// 给出线程运行提示信息
	fprintf(stderr,"thread eleven running\n");

	while(1){
		// 清空接收缓冲区
		rev_length = 0;

		// 组播接收数据
		rev_length = recvfrom(socked, rev_buffer, sizeof(rev_buffer), 0, (struct sockaddr *)&sender, &sender_len);
		
		// 组播发送
        sendto(sock_send, rev_buffer, rev_length, 0, \
                        (struct sockaddr*)&cliaddr, len);
	}

	return NULL;
}

